package com.jeecms.wicool.dao.lottery.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.jeecms.cms.entity.main.CmsUser;
import com.jeecms.common.hibernate3.Finder;
import com.jeecms.common.hibernate3.HibernateBaseDao;
import com.jeecms.common.page.Pagination;
import com.jeecms.wicool.dao.lottery.SnDao;
import com.jeecms.wicool.entity.lottery.Sn;
import com.jeecms.wicool.util.ConstantUtil;
import com.jeecms.wicool.util.SecurityUtil;

@Repository
public class SnDaoImpl extends
		HibernateBaseDao<Sn, Integer> implements SnDao {
	
	@Override
	protected Class<Sn> getEntityClass() {
		// TODO Auto-generated method stub
		return Sn.class;
	}
	public Pagination getPage(String prizeName,Integer status,String sn,int pageNo, int pageSize,CmsUser user) {
		Finder f = Finder.create("from Sn bean where 1=1");
		if (!StringUtils.isBlank(prizeName)){
			f.append(" and bean.lotteryConfig.prizeName like :prizeName");
			f.setParam("prizeName",  "%"+prizeName+"%" );
		}if (status!=null){
			f.append(" and bean.status = :status");
			f.setParam("status",status);
		}if (!StringUtils.isBlank(sn)){
			f.append(" and bean.sn = :sn");
			try {
				f.setParam("sn",  SecurityUtil.aesEncode(sn, ConstantUtil.key) );
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}if(user.getShopId()!=null){
			f.append(" and bean.shop.id = :shopId");
			f.setParam("shopId",user.getShopId());
		}
		f.append(" order by bean.id desc");
		return find(f, pageNo, pageSize);
	}
	
	@Override
	public Sn findById(Integer id) {
		Sn entity = get(id);
		return entity;
	}
	@Override
	public Sn save(Sn bean) {
		getSession().save(bean);
		return bean;
	}
	@Override
	public Sn deleteById(Integer id) {
		Sn entity = super.get(id);
		if (entity != null) {
			getSession().delete(entity);
		}
		return entity;
	}

	@Override
	public List<Sn> getAll(CmsUser user) {
		Finder f= Finder.create("select bean from Sn bean where 1=1 ");
		if(user.getShopId()!=null){
			f.append(" and bean.shop.id = :shopId");
			f.setParam("shopId",user.getShopId());
		}
		f.append(" order by bean.id desc");
		return find(f);
	}
	@Override
	public List<Sn> getSnByLottery(Integer lotteryId) {
		// TODO Auto-generated method stub
		Finder f= Finder.create("select bean from Sn bean where 1=1 ");
		if(lotteryId!=null){
			f.append(" and bean.lotteryConfig.id = :lotteryId");
			f.setParam("lotteryId",lotteryId);
		}
		f.append(" order by bean.id desc");
		return find(f);
	}
}